package mianyang.zhangsan.com.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import mianyang.zhangsan.com.pojo.BookOrder;
import mianyang.zhangsan.com.pojo.Room;
import mianyang.zhangsan.com.pojo.RoomCustom;
import mianyang.zhangsan.com.pojo.RoomType;
import mianyang.zhangsan.com.service.RoomService;
import mianyang.zhangsan.com.service.RoomTypeService;
import mianyang.zhangsan.com.utils.ExcelUtils;
import mianyang.zhangsan.com.utils.Upload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Action;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/room")
public class RoomController {

    @Autowired
    private RoomService roomService;

    @Autowired
    private RoomTypeService roomTypeService;

    /**
     * 前台查询房间信息
     * @param pageNo
     * @param model
     * @return
     */
    @RequestMapping("/frontList")
    public String frontList(@RequestParam("pageNo")int pageNo, Model model){
        Page<Room> roomPage = roomService.queryPages(pageNo);
        List<RoomType> roomTypes = roomTypeService.queryAll();
        model.addAttribute("roomTypes", roomTypes);
        model.addAttribute("rooms", roomPage.getRecords());
        model.addAttribute("pages", roomPage.getPages());
        roomPage.setRecords(null);
        model.addAttribute("page", roomPage);
        return "room/room_front_result";
    }

    /**
     * 后台跳转房间添加界面
     * @return
     */
    @RequestMapping("/toAdd")
    public String toRoomAdd(){
        return "room/room_add";
    }

    /**
     * 后台添加房间信息
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    public String roomAdd(Room room, HttpServletRequest request ){
        System.out.println(room);
        if (room != null){
            if (room.getRoomNo() != "" && room.getRoomNo() != null){
                Room check = roomService.queryRoomInfo(room.getRoomNo());
                if (check != null){
                    return "{\"success\": false}";
                }
            }
        }
        try {
            room.setRoomPhoto(Upload.handlePhotoUpload(request, "roomPhotoFile"));
        } catch (IOException e) {
            e.printStackTrace();
            return "{\"success\": false,\"message\": \"图片格式不正确\"}";
        }
        roomService.addRoom(room);

        return "{\"success\":true}";
    }

    /**
     * 后台跳转房间查询界面
     * @return
     */
    @RequestMapping("/query")
    public String roomQuery(){
        return "room/room_query_result";
    }

    /**
     * 后台查询房间信息
     * @param room
     * @param page
     * @param rows
     * @return
     */
    @RequestMapping(value = "/list", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String list(Room room, Integer page, Integer rows){
        System.out.println(room);
        Page<Room> roomPage = roomService.queryPageByWrapper(page, rows, room);
        JSONObject response = new JSONObject();
        response.put("total", roomPage.getPages());
        JSONArray jsonArray = new JSONArray();
        for (Room item : roomPage.getRecords()){
            String roomType = roomTypeService.queryRoomTypeInfo(item.getRoomType()).getRoomTypeName();
            RoomCustom roomCustom = roomService.packing(roomType, item);
            roomCustom.setRoomPhoto("/upload/" + roomCustom.getRoomPhoto());
            System.out.println(roomCustom);
            Object o = JSON.toJSON(roomCustom);
            jsonArray.add(o);
        }
        response.put("rows", jsonArray);
        return response.toString();
    }

    /**
     * 删除一条房间信息
     * @param roomNo
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String delete(@RequestParam("roomNo") String roomNo){
        int delete = roomService.deleteOne(roomNo);
        System.out.println(delete);
        return "{\"success\": true, \"message\": \"删除成功\"}";
    }

    /**
     * 删除多条房间信息
     * @param roomNos
     * @return
     */
    @RequestMapping("/deletes")
    @ResponseBody
    public String deletes(String roomNos){
        roomService.deletes(roomNos);
        return "{\"success\": true,\"message\": \"删除成功\"}";
    }

    /**
     * 更新房间信息
     * @param room
     * @return
     */
    @RequestMapping("/update")
    @ResponseBody
    public String update(Room room){
        try {
            roomService.update(room);
        } catch (Exception e) {
            e.printStackTrace();
            return "{\"success\": \"false\",\"message\": \"要更新的数据不存在，刷新后重试\"}";
        }
        return "{\"success\": \"false\",\"message\": \"更新成功\"}";
    }

    /**
     * 后台查询可预订的房间信息（空闲的房间）
     * @return
     */
    @RequestMapping("/listAll")
    @ResponseBody
    public String queryList(){
        List<Room> rooms = roomService.queryList();
        JSONArray response = new JSONArray();
        for (Room room : rooms){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("roomNo", room.getRoomNo());
            response.add(jsonObject);
        }
        return response.toString();
    }

    /**
     * 后台导出新闻信息
     * @param room
     * @param response
     */
    @RequestMapping("/outToExcel")
    public void toExcel(Room room, HttpServletResponse response) {
        List<Room> rooms = roomService.queryListByWrapper(room);
        String[] headers = {"房间号", "房间类型", "图片路径", "价格", "楼层", "房间状态", "房间描述"};
        String title = "房间表";
        List<String[]> contents = new ArrayList<>();
        for (Room item : rooms) {
            contents.add(new String[]{item.getRoomNo(), item.getRoomType().toString(), item.getRoomPhoto(), item.getRoomPrice().toString(),
                    item.getFloor(), item.getRoomState(), item.getRoomDesc()});
            OutputStream out = null;
            try {
                out = response.getOutputStream();
                response.setHeader("Content-disposition", "attachment; filename=" + "room.xls");//filename是下载的xls的名，建议最好用英文
                response.setContentType("application/msexcel;charset=UTF-8");//设置类型
                response.setHeader("Pragma", "No-cache");//设置头
                response.setHeader("Cache-Control", "no-cache");//设置头
                response.setDateHeader("Expires", 0);//设置日期头
                ExcelUtils.exportExcel(title, headers, contents, out);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
